from hashlib import md5
import math
import requests
import random
import time
import re
import os

def is_number(value):
    pattern = r'^[-+]?(\d+|\d+\.\d*|\.\d+)([eE][-+]?\d+)?$'
    return bool(re.match(pattern, str(value)))

def handle_text(text,fromLan):
    txt = text.replace("\t", "")

    if len(txt)==1:
        # 如果只有一个字符是换行，则去掉这个字符
        txt = txt.replace("\n", "")
    if fromLan == 'zh':
        # 只有中文的时候才会替换空格，外文不替换，因为单词之间就是空格隔开的
        txt = txt.replace(" ", "")
    return txt

def jump_text(str_text):
    if str_text.startswith('---') or str_text.startswith('#') or str_text == '\n' or str_text == "" or len(str_text) <= 0:
        return True
    if is_number(str_text):
        #如果是纯数字，跳过翻译
        return True
    else:
        return False

def get_process(pcurr,plen):
    str_process = str(round(pcurr / plen, 4))[2:]
    return str_process[0:2]+'.'+str_process[2:]+'%'

def diff_time(s_time, e_time):
    difference = e_time - s_time
    return math.ceil(difference.seconds/60)

def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


'''
栾哥
lqinb luanqinbo1314
20241230002241894
RPA5ccDy9QRGbdTFUiQh

董慧账号
qq923145464 5039805guo
20230307001591074
hA6vyeXkNbxbHJea7fhF

郭蒙
三靠牌 gmly891217
20230307001591116
UB3dtlHLPG35LGB5zs0G

郭东升
20160521000021628
S5irgrIfTwamRSvXY1bW
'''

def getidkey():
    with open('setting.txt','r',encoding='utf-8') as file:
        setting = file.readlines()
    res = [item.replace("\n", "") for item in setting if item.startswith('appid') or item.startswith('appkey')]
    return res[0].split('=')[1], res[1].split('=')[1]

def getLanguage():
    fromLan = ''
    toLan = ''
    print('汉--->俄，请按：1')
    print('俄--->汉，请按：2')
    print('汉--->乌，请按：3')
    print('乌--->汉，请按：4')
    print('英--->俄，请按：5')

    while True:
        tran_type = input('请输入操作：')
        if tran_type == '1':
            fromLan = 'zh';toLan = 'ru'
            break
        elif tran_type == '2':
            fromLan = 'ru';toLan = 'zh'
            break
        elif tran_type == '3':
            fromLan = 'zh';toLan = 'ukr'
            break
        elif tran_type == '4':
            fromLan = 'ukr';toLan = 'zh'
            break
        elif tran_type == '5':
            fromLan = 'en';toLan = 'ru'
            break
        else:
            print('操作错误，请重新输入')
            pass
    return fromLan,toLan


def getLanguageBySettings():
    with open('setting.txt','r',encoding='utf-8') as file:
        setting = file.readlines()
    res = [item.replace("\n","") for item in setting if item.startswith('fromLan') or item.startswith('toLan') ]
    return res[0].split('=')[1],res[1].split('=')[1]

def getFilesList(type='docx'):
    current_directory = os.getcwd()
    all_items = os.listdir(current_directory)
    files = [item for item in all_items if item.endswith(type) and not item.startswith('~')]
    return files

def tran(query,from_lang='zh',to_lang='ru',appid='',appkey=''):

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    salt = random.randint(32768, 65536)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}

    sign = make_md5(appid + query + str(salt) + appkey)
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    time.sleep(0.1)
    if 'error_code' in result:
        print(f"\033[31m{query}\033[0m",result)
        return query
    else:
        trans_result = result["trans_result"]
        res = [ i['dst'] for i in trans_result ]
        return '\n'.join(res)